<?php
include_once $_SERVER['DOCUMENT_ROOT'].'/lib/Cache.php';
include_once $_SERVER['DOCUMENT_ROOT'].'/lib/detectlanguage.php';
use \DetectLanguage\DetectLanguage;

class DetectLang{
	protected static $_instance;
	private static $key='872146ae9f8afe7ce2f0aa5064f69400';
	
	private function __construct(){}
	private function __clone(){}
	public static function inst(){
	  if( null===self::$_instance ){
	    self::$_instance=new self();
		}
		return self::$_instance;
	}
	
	protected $errors=array('err'=>array(),'wrn'=>array());
	protected function error($msg){ $this->errors['err'][]=$msg; return false;}
	protected function warning($msg){ $this->errors['wrn'][]=$msg; return false;}
	public function getError(){ return $this->errors['err'][ count($this->errors['err'])-1 ]; }
	public function getErrors(){ return $this->errors['err']; }
	public function getWarning(){ return $this->errors['wrn'][ count($this->errors['wrn'])-1 ]; }
	public function getWarnings(){ return $this->errors['wrn']; }


	public function detect($str){
	  if( $tst=Cache::inst()->get('detect:'.md5($str)) ) return $tst;
		DetectLanguage::setApiKey(self::$key);
		try{
		  $results = DetectLanguage::simpleDetect($str);
		}catch(Exception $e){
		  return $this->error( 'DetectLanguage : '.$e->getMessage() );
		}
    
    if(!$results){
      $results = DetectLanguage::getStatus();
      $this->error( 'DetectLanguage Limits: '.print_r($results,1) );
		}
		
		Cache::inst()->set('detect:'.md5($str),$results);
		return $results;
	}
}
?>
